$(function () {
    xsht_init();
})


function xsht_init() {
    //采购方公司加载
    $("[name='xsht_ssgs']").jgbmtree($("[name='xsht_ssbm']"), $("[name='xsht_cjr']"), '', '')
    //合作方加载
    $("[name='xsht_kh']").qyjgzcombobox();
    var options = getXshtGridOption("");
    $('#xsht-grid').datagrid(options);
}

function xsht_search() {
    var zt = $("#xsht-toolbar input[name='xsht_zt']").val();
    var htbh = $("#xsht-toolbar input[name='xsht_htbh']").val();
    var gys = $("#xsht-toolbar input[name='xsht_kh']").val();
    var xhtbm = $("#xsht-toolbar input[name='xsxt_htbm']").val();
    var startDate = $('#qdrq_start').datebox('getValue');
    var endDate = $('#qdrq_end').datebox('getValue');
    $('#xsht-grid').datagrid('load',
        {
            zt: zt,
            htbh: htbh,
            hzfId: gys,
            xhtbm: xhtbm,
            startDate: startDate,
            endDate: endDate
        }
    );
}

var xshthref;
var isXshtEdit;
//新增销售合同
function xsht_addItem(title, action) {

    var href = $.webPath() + "/htgl/xshtgl/xshtgl_content";
    xshthref = $.webPath() + "/htgl/xshtgl/" + action;
    isXshtEdit = "no";
    xsht_showDialog(title, href, "");
}

function xsht_editItem(title, action) {
    var record = $("#xsht-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要修改的记录!", "info");
        return;
    }
    var href = $.webPath() + "/htgl/xshtgl/xshtgl_content?xshtId=" + record.id;
    xshthref = $.webPath() + "/htgl/xshtgl/" + action;
    isXshtEdit = "yes";
    xsht_showDialog(title, href, record.zt);
}

function xsht_transferItem() {
    var record = $("#xsht-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要同步的记录!", "info");
        return;
    }
    $.messager.confirm('确认', '同步会删除原有明细信息，是否确认同步', function (r) {
        if (r) {
            $.post($.webPath() + '/htgl/xshtgl/transfer_xsht', {xshtId: record.id}, function (data) {
                var obj = eval('(' + data + ')');
                if (obj.statusCode == '200') {
                    $('#xsht-grid').datagrid('reload');
//                    $('#xsht_layout').layout('panel', 'center').panel('refresh');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                } else
                    $.messager.alert('提示', obj.message, 'info');
            });
        }
    });
}

var xsht_win;
//新增、修改企业法人弹出界面
function xsht_showDialog(title, href, xshtzt) {
    var button
    if (xshtzt == '已保存')
        button = [
            {text: '保存', handler: xsht_saveItem}
//            {text: '提交', handler: xsht_commitItem}
        ];
    else
        button = [
            {text: '保存', handler: xsht_saveItem}
        ];

    xsht_win = $.window({
        title: title,
        iconCls: 'icon-add2',
        url: href,
        width: 1024,
        height: 500,
        buttons: button,
        onBeforeClose: function () {
            window.parent.destroy('xsht-uploadify');
        }
    });
}

function xsht_saveItem() {
    $("#xsht_mx").edatagrid('saveRow');
    $('#xshtglForm').tabs('select', "合同信息");
    $("#xshtglForm").form('submit', {
        url: xshthref,
        onSubmit: function (param) {
            var gdata = $("#xsht_gspzList").edatagrid("getChecked");
            var bzjfs=$("#xsht_bzjfs").val();
            if (!gdata.length && bzjfs!=2) {
                $('#xshtglForm').tabs('select', "公式选择");
                $.messager.alert("提示", "请选择公式!", "waring");
                return false;
            }
            if(gdata.length!=0){
                $("#xsht_gspz").val(gdata[0].id);
            }
            var data = $('#xsht_mx').edatagrid("getData");
            if (!data.rows.length) {
                $('#xshtglForm').tabs('select', "合同明细");
                $.messager.alert("提示", "请填写合同明细!", "waring");
                return false;
            }
            var arrayPrefix = 'xsht.htmxList';
            //物资计划明细
            var paramString = "{";
            //物资计划明细
            for (var i = 0; i < data.rows.length; i++) {
                if (data.rows[i].sbsl == 0 || data.rows[i].sbsl == null) {
                    $('#xshtglForm').tabs('select', "合同明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的数量不能为0 !', 'info');
                    return false;
                } else if (data.rows[i].hsj == 0 || data.rows[i].hsj == null) {
                    $('#xshtglForm').tabs('select', "合同明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的含税单价不能为0 !', 'info');
                    return false;
                } else if (data.rows[i].bhsj == 0 || data.rows[i].bhsj == null) {
                    $('#xshtglForm').tabs('select', "合同明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的不含税单价不能为0 !', 'info');
                    return false;
                } else if (data.rows[i]['cd.id'] == null || data.rows[i]['cd.id'] == '') {
                    $('#xshtglForm').tabs('select', "合同明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的产地不能为空 !', 'info');
                    return false;
                }
                var objectString = $.toJSONStringPrefix(data.rows[i], arrayPrefix + "[" + i + "].");
                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
            }
            if (data.rows && data.rows.length > 0)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            return $(this).form('validate');
        },
        success: function (data) {
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                if (isXshtEdit == "yes") {
                    $(xsht_win).window('close');
                    $('#xsht-grid').datagrid('reload');
//                    $('#xsht_layout').layout('panel', 'center').panel('refresh');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                } else {
//                    $.messager.confirm('确认', '是否编辑合同文本', function (r) {
//                        if (r) {
//                            $(xsht_win).window('close');
//                            $('#xsht-grid').datagrid('reload');
//                            $('#xsht_layout').layout('panel', 'center').panel('refresh');
//                            $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
//                            var href = $.webPath() + "/htgl/xshtgl/xshtgl_content?xshtId=" + obj.xshtId;
//                            xshthref = $.webPath() + "/htgl/cghtgl/edit_cght";
//                            isXshtEdit="yes";
//                            xsht_showDialog("修改销售合同", href, "已保存");
////                            $('#xshtglForm').tabs('select', "合同文本");
//                        } else {
                    $(xsht_win).window('close');
                    $('#xsht-grid').datagrid('reload');
//                    $('#xsht_layout').layout('panel', 'center').panel('refresh');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
//                        }
//                    });
                }
            } else {
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}

function xsht_commitItem() {
    var row = $('#xsht-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否确认提交此销售合同', function (r) {
            if (r) {
                $.post($.webPath() + '/htgl/xshtgl/commit_xsht', {xshtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#xsht-grid').datagrid('reload');
//                        $('#xsht_layout').layout('panel', 'center').panel('refresh');
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要提交的销售合同", 'info');
    }
}

function xsht_destroyItem() {
    var row = $('#xsht-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否确认删除此销售合同', function (r) {
            if (r) {
                var index = $('#xsht-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/htgl/xshtgl/delete_xsht', {xshtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#xsht-grid').datagrid('deleteRow', index);
                        $('#xsht-grid').datagrid('reload');
//                        $('#xsht_layout').layout('panel', 'center').panel('refresh');
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要删除的销售合同", 'info');
    }
}

function xsht_agreeItem() {
    var row = $('#xsht-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '合同履约后无法开单，是否确认履约此销售合同', function (r) {
            if (r) {
                $.post($.webPath() + '/htgl/xshtgl/agree_xsht', {xshtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#xsht-grid').datagrid('reload');
//                        $('#xsht_layout').layout('panel', 'center').panel('refresh');
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要履约的销售合同", 'info');
    }
}


function xsht_tj1() {
    var row = $('#xsht-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否确认提交此销售合同', function (r) {
            if (r) {
                $.post($.webPath() + '/htgl/xshtgl/tj_xsht', {xshtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#xsht-grid').datagrid('reload');
//                        $('#xsht_layout').layout('panel', 'center').panel('refresh');
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要提交的销售合同", 'info');
    }
}


function xsht_stopItem() {
    var row = $('#xsht-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '合同终止后无法开单，是否确认终止此销售合同', function (r) {
            if (r) {
                $.post($.webPath() + '/htgl/xshtgl/stop_xsht', {xshtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#xsht-grid').datagrid('reload');
//                        $('#xsht_layout').layout('panel', 'center').panel('refresh');
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要终止的销售合同", 'info');
    }
}

function getXshtGridOption(type) {
    var options = {
        url: $.webPath() + "/htgl/xshtgl/xshtList",
        toolbar: "#xsht-toolbar",
        fitColumns: true,
        singleSelect: true,
        pagination: true,
        pageNumber: 1,
        fit: true,
        rownumbers: true,
        onLoadSuccess: function (target) {
            $("#xsht-del").css('display', 'none');
            $("#xsht-edit").css('display', 'none');
            $("#xsht-commit").css('display', 'none');
            $("#xsht-agree").css('display', 'none');
            $("#xsht-stop").css('display', 'none');
            $(this).datagrid('selectRow', 0);

            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');

        },
        loadFilter: function (data) {
            $.each(data.rows, function () {
                if (this.xslx) {
                    this.xslx = this.xslx == "kcxs" ? "库存销售" : "直达到货";
                }
                if (this.zt) {
                    this.zt = this.zt == 'yly' ? "已完结" : this.zt == 'yzz' ? "已终止" : this.zt == 'ytj' ? "已提交" : this.zt == 'ysp' ? "已审批" : "已保存";
                }
                if (!this.wlyl)
                    this.wlyl = 0;
                this.wlyl = this.sbsl - this.wlyl;
            });
            return data;
        },
        onSelect: function (rowIndex, rowData) {

            if (rowData) {
                if (rowData.zt == '已保存') {
                    $("#xsht-edit").css('display', '');
                    if (rowData.xslx != '直达到货') {
                        $("#xsht-del").css('display', '');
                        $("#xsht-commit").css('display', '');
                        $("#xsht-transfer").css('display', '');
                    } else {
                        $("#xsht-del").css('display', 'none');
                        $("#xsht-commit").css('display', 'none');
                        $("#xsht-transfer").css('display', '');
                    }
                    $("#xsht-agree").css('display', 'none');
                    $("#xsht-stop").css('display', 'none');
                    // if(rowData && rowData.htms=='xsms'){
                    // $("#xsht-tj").show();
                    //  $("#xsht-commit").css('display', 'none');
                    // }else{
                    // $("#xsht-tj").hide();
                    // }
                } else if (rowData.zt == '已审批') {
                    $("#xsht-edit").css('display', 'none');
                    $("#xsht-del").css('display', 'none');
                    $("#xsht-commit").css('display', 'none');
                    $("#xsht-transfer").css('display', 'none');
                    $("#xsht-agree").css('display', '');
                    $("#xsht-stop").css('display', '');
                    //  $("#xsht-tj").hide();
                } else {
                    $("#xsht-commit").css('display', 'none');
                    $("#xsht-transfer").css('display', 'none');
                    $("#xsht-edit").css('display', 'none');
                    $("#xsht-del").css('display', 'none');
                    $("#xsht-agree").css('display', 'none');
                    $("#xsht-stop").css('display', 'none');
                }
            }
        }, onDblClickCell: function (index, field, value) {
            if (field == "htbm") {
                $("#xsht-edit:visible").click();
//                var record = $("#xsht-grid").datagrid("getSelected")
//                if (record.zt == '已保存')
//                    xsht_editItem('修改销售合同', 'edit_xsht');
            }
        }
    };
    if (type == "kcxs") {
        var columns = {columns: [
            [
                {field: 'htbm', title: '合同号', align: 'center', width: 50, formatter: xshtCell},
                {field: 'hzf_qc', title: '客户', align: 'center', width: 50},
                {field: 'xslx', title: '类型', align: 'center', width: 20},
                {field: 'sbsl', title: '重量', align: 'right', formatter: function (value) {
                    var sl = formatSlForHtml(value, ",");
                    return sl;
                }, width: 50},
                {field: 'wlyl', title: '未履约量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 40},
                {field: 'sbr_xm', title: '申报人', align: 'center', width: 20},
                {field: 'qdrq', title: '签订日期', align: 'center', width: 30},
                {field: 'zt', title: '状态', width: 20, align: 'center', formatter: formatXshtSp}
            ]
        ]}
        options = $.extend(options, columns);
    } else if (type == "zddh") {
        var columns = {columns: [
            [
                {field: 'htbm', title: '合同号', align: 'center', width: 50, formatter: xshtCell},
                {field: 'hzf_qc', title: '客户', align: 'center', width: 50},
                {field: 'xslx', title: '类型', align: 'center', width: 20},
                {field: 'sbsl', title: '重量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'wlyl', title: '未履约量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 40},
                {field: 'sbr_xm', title: '申报人', align: 'center', width: 20},
                {field: 'qdrq', title: '签订日期', align: 'center', width: 30},
                {field: 'cght_htbm', title: '采购合同', align: 'center', width: 50},
                {field: 'zt', title: '状态', width: 20, align: 'center', formatter: formatXshtSp}
            ]
        ]}
        options = $.extend(options, columns);
    } else {
        var columns = {columns: [
            [
                {field: 'htbm', title: '合同号', align: 'center', width: 50, formatter: xshtCell},
                {field: 'xsxt_htbm', title: '来源系统合同号', align: 'center', width: 50},
                {field: 'htms', title: '合同模式', align: 'center', formatter: function (value) {
                    if (value == 'xxms') {
                        return "线下"
                    } else {
                        return "线上"
                    }
                }, width: 30},
                {field: 'extension', title: '是否居中结算订单', align: 'center', formatter: function (value) {
                    if (value == 'mid') {
                        return "是"
                    } else {
                        return "否"
                    }
                }, width: 20},
                {field: 'hzf_qc', title: '客户', align: 'center', width: 90},
                {field: 'xslx', title: '类型', align: 'center', width: 40},
                {field: 'sbsl', title: '重量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 40},
                {field: 'wlyl', title: '未履约量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 40},
                {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 40},
                {field: 'sbr_xm', title: '申报人', align: 'center', width: 20},
                {field: 'qdrq', title: '签订日期', align: 'center', width: 30},
                {field: 'zt', title: '状态', width: 20, align: 'center', formatter: formatXshtSp}
            ]
        ]}
        options = $.extend(options, columns);
    }
    return options;
}

function formatXshtSp(val, row) {
    if (!row.processInstanceId || row.xslx == '直达到货') {
        return val;
    } else {
        return '<a href="javascript:viewXshtFlowPicture();" style="color: red">' + val + '</a>';
    }
}

function viewXshtFlowPicture() {
    var row = $('#xsht-grid').datagrid('getSelected');
    $.window({
        title: "流程历史",
        iconCls: 'icon-add2',
        url: $.webPath() + "/flow/publish/flowPicture?processInstanceId=" + encodeURI(encodeURI(row.processInstanceId)) + "&businessNo=" + row.htbm,
        width: 650,
        height: 500,
        closed: true,
        modal: true,
        isMax: true
    });
}


